package at.fhj.mobsecdev.cookit.webrequests;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import at.fhj.mobsecdev.cookit.R;
import at.fhj.mobsecdev.cookit.model.User;
import at.fhj.mobsecdev.cookit.util.LoadingIndicator;
import at.fhj.mobsecdev.cookit.util.Tuple;

/**
 *  Calls Registration Web Service
 */
public class RegistrationWebCall extends AsyncTask<User, Void, Tuple<Integer, String>> {

	private Registration caller;
	private ProgressDialog dialog;
	private Context context;
	
	public RegistrationWebCall(Registration caller, Activity activity)
	{
		this.caller = caller;
		this.context = activity;
	}
	
	protected void onPreExecute() {
	    dialog = new LoadingIndicator(context).createIndicator();
	    dialog.show();
	}
	
	/**
	 * Calls web service
	 * @return Tuple, that contains HTTP status code and return message (entity)
	 */
	@Override
	protected Tuple<Integer, String> doInBackground(User... user) {
		HttpResponse response = null;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		User userToRegister = user[0];
		try {
			String webServiceUrl = WebServiceUrls.REST_URL + WebServiceUrls.REGISTRATION;
			
			HttpPost httppost = new HttpPost(webServiceUrl);

			/* Build Http-Form */
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
	        nameValuePairs.add(new BasicNameValuePair("username", userToRegister.getUsername()));
	        nameValuePairs.add(new BasicNameValuePair("password", userToRegister.getPassword()));
	        nameValuePairs.add(new BasicNameValuePair("email", userToRegister.getEmail()));
	        try {
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
			} catch (UnsupportedEncodingException e1) {
				return null;
			}

			Log.i("RegisterUser", "request " + httppost.getRequestLine());
			try {
				response = httpclient.execute(httppost);
			} catch (ClientProtocolException e) {
				return null;
			} catch (IOException e) {
				return null;
			}
				if (response != null) {
					Log.i("RegisterUser", "response "+ response.getStatusLine().toString());
				}
				
				/* If call was successful, return status code + entity, otherwise null */
				return response != null ? new Tuple<Integer, String>(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity())) : null;
		} catch (Exception e) {
			return null;
		}
	}
	
	protected void onPostExecute(Tuple<Integer, String> result) {
		super.onPostExecute(result);
		if (dialog.isShowing()) {
			dialog.dismiss();
		}
		
		if(result == null) { //Call was not successful
			caller.registrationFail(context.getResources().getString(R.string.unknown_reason));
			return;
		}
		if(result.x == HttpStatus.SC_OK) //Call was successful, registration was successful
		{
			caller.registrationSuccess();
		}
		else if(result.x == 400) //Call was successful, registration was not successful
		{
			caller.registrationFail(result.y);
		}
		else { //Call was successful, registration was not successful (unknown reason)
			caller.registrationFail(result.y);
		}
	}
	
	/**
	 * Interface, which specifies the methods that are called after the webservice call. The calls forward either the list of
	 * parsed recipes or error information.
	 */
	public interface Registration
	{
		void registrationSuccess();
		
		void registrationFail(String error);
	}

}
